<template>
    <div>
        <basic-container>
            <div class="app-container">
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
                    <el-form-item label="日期查询">
                        <el-date-picker v-model="value" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="产品SN">
                        <el-input  style="width: 100%;" v-model="queryParams.sequence" placeholder="请输入产品SN码"  clearable />
                    </el-form-item>
                    <el-form-item label="数据类型">
                        <el-select v-model="queryParams.name" placeholder="请选择" style="width: 100%;" clearable >
                                <el-option v-for="item in menuList" :key="item.gather_id" :label="item.name"
                                    :value="item.name">
                                </el-option>
                            </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-form-item label="设备名称">
                            <el-select v-model="queryParams.facility_id" placeholder="请选择" style="width: 100%;" clearable>
                                <el-option v-for="item in imagelist" :key="item.facility_id" :label="item.name"
                                    :value="item.facility_id"  >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    </el-form-item>
                </el-form>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-download" size="mini"
                            @click="handleExport">导出</el-button>
                    </el-col>
                </el-row>
            </div>

           <div class="bigbox">
            <div style="flex: 1;">
                <template>
                    <div v-if="toNum === 1" class="back-arrow" @click="gobock">
                        <i class="el-icon-arrow-left"></i>
                    </div>
                    <el-table :data="menuList" v-loading="loading" element-loading-text="拼命加载中"
                        element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
                        ref="table" style="width: 100%">
                        <el-table-column prop="sequence" label="产品编码" align="center" width="240">
                            <template slot-scope="scope">
                                <div class="clickable-cell" @click="handleCellClick(scope.row)">{{ scope.row.sequence }}</div>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
               
            </div>
            <div style="flex: 9;">
               <div ref="chart" style="width: 100%; height: 600px;"></div>
            </div>
           </div>
           <pagination v-show="toNum > 0" :total="toNum" :page.sync="queryParams.index" :limit.sync="queryParams.size"
            @pagination="getList" />
        </basic-container>
    </div>
</template>

<script>
import { eidrepair, dlerepair, gettemplatelist, eidTemplate } from "@/api/image";
import { getentering } from "@/api/gather";

import * as echarts from 'echarts';
import {
    getkindList,
} from "@/api/data";
import { roleStation, } from "@/api/flow";
import { mapGetters } from "vuex";
export default {
    data() {
        return {
            chart: null,
            toNum: 0,
            option: {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: []
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: []
                },
                yAxis: {
                    type: 'value',
                    min: 0,
                    max: 18
                },
                series: [

                ]
            },
            reworkList: [],
            imagelist: [],
            reworkValue: '',
            message: '',
            aircraftId: null,
            tabPosition: 'left',
            loading: false,
            dialogVisible: false,
            valueName: '',
            total: 0,
            queryParams: {
                index: 1,
                size: 10,
                finish: null,
                start: null,
                name:null,
                facility_id: null,
                sequence: null,
            },

            optionname: '',
            optionserials: '',
            optionId: '',
            courseId: null,
            optionrole: [],
            options: [
                {
                    value: 0,
                    label: '未加工完成'
                },
                {
                    value: 1,
                    label: '合格'
                },
                {
                    value: 2,
                    label: '不合格'
                }, {
                    value: 3,
                    label: '报废'
                }],
            open: false,
            title: "",
            dataList: [],
            value: '',
            form: {},
            menuList: [],
            rules: {
                aircraft: [
                    { required: true, message: "机种名称不能为空", trigger: "blur" }
                ],
                name: [
                    { required: true, message: "工艺名称不能为空", trigger: "blur" }
                ],
                formula_id: [
                    { required: true, message: "工艺配方不能为空", trigger: "blur" }
                ],

            }
        }
    },
    created() {
        var today = new Date();
        var year = today.getFullYear();
        var month = today.getMonth() + 1;
        var day = today.getDate();
        var formattedDate = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
        this.queryParams.start = formattedDate
        this.queryParams.finish = formattedDate
        this.value = [formattedDate, formattedDate]
        this.getList()
        this.getroleStation()
    },
    beforeDestroy() {
        if (this.chart) {
            window.removeEventListener('resize', this.chart.resize)
            this.chart.dispose()
        }
    },
    computed: {
        ...mapGetters(["userInfo", "menu"]),
    },
    mounted() {
        this.initChart()
        this.gitAmagelist()

    },
    methods: {
        initChart() {
            this.chart = echarts.init(this.$refs.chart);
            this.chart.setOption(this.option);
            window.addEventListener('resize', this.chart.resize);
     
            this.chart.on('legendselectchanged', (params) => {
                console.log(1111);
                // 如果你还需要做其他处理，比如更新 yAxis
                const selectedName = Object.keys(params.selected).find(name => params.selected[name]);
                const selectedSeries = this.menuList.find((item, index) => `${item.name}-${index}` === selectedName);
                if (selectedSeries && selectedSeries.message) {
                    const floor = (selectedSeries.message && selectedSeries.message.floor) || 0;
                    const upper = (selectedSeries.message && selectedSeries.message.upper) || 0;
                    this.option.yAxis.min = floor;
                    this.option.yAxis.max = upper;
                    this.chart.setOption({
                        yAxis: {
                            min: floor,
                            max: upper
                        }
                    });
                }
            });
        },

        /** 查询菜单列表 */
        getList() {
            this.loading = true;
            getentering(this.queryParams).then(response => {
                this.menuList = response.data.data;
                const floors = this.menuList.map(item => (item.message && item.message.floor) || 0);
                const uppers = this.menuList.map(item => (item.message && item.message.upper) || 0);
                this.option.yAxis.min = Math.min(...floors);
                this.option.yAxis.max = Math.max(...uppers);
                 this.toNum = response.data.total;
                this.chart.setOption(this.option, true);
                this.loading = false;
            });
        },

        handleQuery() {
            this.queryParams.start = this.value == null ? null : this.value.length > 0 ? this.value[0] : null
            this.queryParams.finish = this.value == null ? null : this.value.length > 0 ? this.value[1] : null
            this.getList();
            if(this.menuList.length == 0){
                this.option.series = []
                console.log(this.menuList,'1111111111111');
                this.option.legend = {};
                this.option.yAxis.min = 0
                this.option.yAxis.max = 0
            }
           
            
        },
       //导出
        handleExport() {
            this.$confirm('是否将数据导出为EXcel文档？').then(() => {
                const params = new URLSearchParams();
                this.value == null ? '' : params.append('start', this.value[0]);
                this.value == null ? '' : params.append('finish', this.value[1]);
                this.queryParams.sequence == null ? '' : params.append('sequence', this.queryParams.sequence);
                this.queryParams.facility_id == null ? '' : params.append('facility_id', this.queryParams.facility_id);
                const url = new URL('http://192.168.10.252:8080/api/gathers/output');
                // const url = new URL('http://118.24.138.196:9005/api/gathers/output');
                url.search = params.toString();
                window.location.href = url.toString();
            })
        },

        // 返工模板
        handlRework(row) {
            console.log(row);
            this.aircraftId = row.aircraft_id
            this.courseId = null

            this.dialogVisible = true;
            let data = {
                aircraft_id: row.aircraft_id
            }
            gettemplatelist(data).then(res => {
                console.log(res);
                this.reworkList = res.data.data
                this.courseId = row.course_id
            })
        },
        TemplateDetermination() {
            let objData = {
                course_id: this.courseId,
                template_id: this.reworkValue,
                aircraft_id: this.aircraftId,
                message: this.message,
            }
            eidTemplate(objData).then(res => {
                console.log(res);
                this.$message({
                    message: "更新成功",
                    type: "success",
                });
                this.getList()
                this.dialogVisible = false;
            })
        },
        // 获取pLC设备
        getroleStation() {
            roleStation().then(res => {
                this.optionrole = res.data.data
            })
        },
        // 表单重置
        reset() {
            this.form = {
                repairs: [],
                course_id: null,
                mark: null,
                message: null,
                start: null,
                stop: null,

            };
        },
        handleUpdate(row) {

            this.reset()
            this.form = row
            this.dataList = row.repairs.flat()
            this.open = true;
            this.title = "修改工站";
        },

        handleDelete(row) {

            let messsId = {
                course_id: row.course_id
            }
            this.$confirm('是否确认删除名称为"' + row.aircraft + '"的工艺路径？')
                .then(() => {
                    dlerepair(messsId).then(() => {
                        this.$message({
                            message: "删除成功",
                            type: "success",
                        });
                        this.open = false;
                        this.getList();
                        this.reset();
                    });
                })
                .catch(() => { });
        },
        cancel() {
            this.open = false;
            this.getList();
            this.reset();
        },
        handleAdd() {
            this.open = true;
            this.reset();
            this.dataList = []
            this.value = ''
            this.valueName = ''
            this.title = "新增路径";
        },
        addprocess() {
            for (var i = 0; i < this.optionrole.length; i++) {

                if (this.valueName == this.optionrole[i].facility_id) {
                    this.optionserials = this.optionrole[i].serials
                    this.optionname = this.optionrole[i].name
                    this.optionId = this.optionrole[i].facility_id
                }
            }
            for (var j = 0; j < this.dataList.length; j++) {
                if (this.dataList[j].sequence == this.value && this.dataList[j].facility_id == this.optionId) {
                    return this.$message.error('已经有相同步骤了');
                }
            }
            this.dataList.push({
                name: this.optionname,
                serials: this.optionserials,
                sequence: this.value,
                facility_id: this.optionId
            })
            this.value = ''
            this.valueName = ''
            this.dataList.sort(function (a, b) {
                return parseInt(a.sequence) - parseInt(b.sequence);
            })
        },
        handleDatalist(index) {
            this.dataList.splice(index, 1);
        },
        gitAmagelist() {
            getkindList(this.queryParams).then((response) => {
                this.imagelist = response.data.data;
                console.log(this.imagelist, "99999999999");
            });

        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    let sequenceMap = {};
                    for (var i = 0; i < this.dataList.length; i++) {
                        let currentSequence = this.dataList[i].sequence;
                        let currentFacilityId = this.dataList[i].facility_id;
                        if (!sequenceMap[currentSequence]) {
                            sequenceMap[currentSequence] = { ft_ids: [] };
                        }
                        sequenceMap[currentSequence].ft_ids.push(currentFacilityId);
                    }
                    this.form.repairs = Object.values(sequenceMap);

                    eidrepair(this.form).then(() => {
                        this.$message({
                            message: "修改成功",
                            type: "success",
                        });
                        this.open = false;
                        this.getList();
                        this.reset();
                    });
                }

            });
        },
        handlePreview(imageUrl) {
            console.log('预览图片数据:', imageUrl); // 调试用
            this.$alert('<img src="data:image/jpeg;base64,' + imageUrl + '" style="width: 100%;">', '图片预览', {
                dangerouslyUseHTMLString: true,
                showConfirmButton: false
            });
        },
        handleCellClick(row) {
            this.queryParams.sequence = row.sequence
            this.option.series = [];
            this.option.legend.data = [];
            this.chart.setOption(this.option, true);
            // 在 menuList 中查找匹配的数据
            const matchedData = this.menuList.filter(item => item.sequence === row.sequence);
            if (matchedData.length > 0) {
                // 更新图表数据
                const floors = matchedData.map(item => (item.message && item.message.floor) || 0);
                const uppers = matchedData.map(item => (item.message && item.message.upper) || 0);
                // 更新图例数据
                const legendData = matchedData.map((item, index) => `${item.name}-${index}`);
                this.option.legend = {
                    data: legendData,
                    selectedMode: 'single',
                    selected: {}
                };
                
                // 设置默认选中第一个
                legendData.forEach((name, index) => {
                    this.option.legend.selected[name] = index === 0;
                });

                // 更新系列数据
                this.option.series = matchedData.map((item, index) => {
                    return {
                        name: `${item.name}-${index}`,
                        type: 'line',
                        stack: 'Total',
                        data: (item.message && item.message.data) || []
                    };
                });

                // 更新Y轴范围
                this.option.yAxis.min = Math.min(...floors);
                this.option.yAxis.max = Math.max(...uppers);

                // 更新图表
                this.chart.setOption(this.option, true);
            }
        },
        gobock(){
            this.queryParams.sequence = null
            this.queryParams.name = null
            this.getList()
        }
    }
};
</script>

<style lang="scss">
.demo-table-expand {
    font-size: 0;

}

.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}

.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}

.chengHigh {
    .el-tabs__item {
        height: 60px !important;
        line-height: 60px !important;
        font-size: 16px !important;
        padding: 0 40px !important;
    }

}

.SecondaryContent {
    width: 100%;
    display: flex;

    .ContentItem {
        flex: 1;
    }
}

.Contentarea {
    display: flex;


}

.using {
    font-size: 16px;
    padding: 10px 0;
    width: 50%;

    text-align: center;

}

.parallel {
    font-size: 16px;
    padding: 10px 0;
    width: 50%;

}

.table {
    display: flex;
    justify-content: space-around;
    font-size: 14px;
    line-height: 40px;
    font-weight: 600;
    height: 45px;
    background-color: #f8f8f9;
    color: #515a6e;
    border-bottom: 1px solid #EBEEF5;
}
.bigbox{
    display: flex;
}
.clickable-cell {
    cursor: pointer !important;
}
.back-arrow {
    cursor: pointer !important;
    padding: 10px;
    margin-bottom: 10px;
    display: inline-block;
    
    i {
        font-size: 20px;
        color: #409EFF;
        
        &:hover {
            color: #66b1ff;
        }
    }
}
</style>
